<template>
    <div id="Home" class="y-flex">
        <van-nav-bar
            title="地图"
            left-text="返回"
			right-text="去这里"
            left-arrow
            @click-left="toMap"
			@click-right="onClickRight"
        />  
		
        <div id="atlas"></div>
        <!-- <van-button type="primary" @click="buttonPosition" icon="location-o" :loading="loading">定位</van-button> -->
    </div>
</template>

<script>
import { InitMap,ToEnd } from '@/utils/tmap'
export default {
    name: 'Index',
    data() {
        return {
			addressname:"",
            map:null,
			lat:0.0,
			lng:0.0,
			center:null,
			from:null,
			markerArr:[],
			shopInfo:[]
        }
    },
    created() {
		this.shopInfo = this.$route.query.shopInfo
        this.addressname = this.$route.query.addressname
		this.mapTX()
    },
    methods: {
        // onClickLeft() {
        //     this.$router.go(-1)
        // },
		toMap() {
			if(this.shopInfo){
				this.$router.push({
                path: '/shopDetail',
                query: {
                    shopInfo: this.shopInfo
                }
            })
			}else{
				this.$router.go(-1)
			}
            
        },
        mapTX() {
			InitMap().then(data => {
				new TMap.service.Geocoder().getLocation({"address":this.addressname}).then(data=>{
					this.center = data.result.location
					this.map = new TMap.Map(document.getElementById('atlas'), {
						// 这里经纬度代理表进入地图显示的中心区域
						center: this.center,
						zoom: 15,
						zoomControl: true,
					})
					var geolocation = new qq.maps.Geolocation("FYHBZ-XDAWF-7UCJN-JIH44-UKENZ-2EBU4", "myapp");
					var _this = this
					geolocation.getLocation(res =>{
						console.log("获取本地位置")
						this.lat = res.lat
						this.lng = res.lng
						this.from = new TMap.LatLng(_this.lat,_this.lng);
							
						this.markerArr =[
							{
								id: "start",
								styleId: "start",
								position: this.from,
							},
							{
								id: "end",
								styleId: "end",
								position: this.center,
							},
						]
						var marker = new TMap.MultiMarker({
							id: "marker-layer", //图层id
							map: this.map,
							styles:{
								'start': new TMap.MarkerStyle({
							          width: 25,
							          height: 35,
							          anchor: { x: 16, y: 32 },
							          src:"https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png",
								}),
								'end': new TMap.MarkerStyle({
							          width: 25,
							          height: 35,
							          anchor: { x: 16, y: 32 },
							          src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png",
								}),
							},
							geometries: this.markerArr
						})
					},err=>{
						this.lat = 24.6337600
						this.lng = 118.0961618
						this.from = new TMap.LatLng(24.6337600,118.0961618);
						this.markerArr =[
							{
								id: "start",
								styleId: "start",
								position: this.from,
							},
							{
								id: "end",
								styleId: "end",
								position: this.center,
							},
						]
						var marker = new TMap.MultiMarker({
							id: "marker-layer", //图层id
							map: this.map,
							styles:{
								'start': new TMap.MarkerStyle({
							          width: 25,
							          height: 35,
							          anchor: { x: 16, y: 32 },
							          src:"https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png",
								}),
								'end': new TMap.MarkerStyle({
							          width: 25,
							          height: 35,
							          anchor: { x: 16, y: 32 },
							          src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png",
								}),
							},
							geometries: this.markerArr
						})
					},{timeout: 3})
					
				})		
			})
		},
		onClickRight(){
			this.selfAdaptionMarker(this.markerArr)
			this.getPath()
		},
		getPath(){
			var url="https://apis.map.qq.com/ws/direction/v1/driving/"; //请求路径
			url+=`?from=${this.lat},${this.lng}`;  //起点坐标
			url+=`&to=${this.center.lat},${this.center.lng}`;  //终点坐标
			url+="&output=jsonp&callback=To" ;  //指定JSONP回调函数名，本例为cb
			url+="&key=FYHBZ-XDAWF-7UCJN-JIH44-UKENZ-2EBU4"
			console.log(url)
			ToEnd(url).then(ret =>{
				var coors = ret.result.routes[0].polyline, pl = [];
				//坐标解压（返回的点串坐标，通过前向差分进行压缩，因此需要解压）
				var kr = 1000000;
				for (var i = 2; i < coors.length; i++) {
				    coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
				}
				//将解压后的坐标生成LatLng数组
				for (var i = 0; i < coors.length; i += 2) {
				    pl.push(new TMap.LatLng(coors[i], coors[i+1]));
				}
				this.display_polyline(pl)//显示路线	
			})
		},
		display_polyline(pl){
		    //创建 MultiPolyline显示折线
		    var polylineLayer = new TMap.MultiPolyline({
		        id: 'polyline-layer', //图层唯一标识
		        map: this.map,//绘制到目标地图
		        //折线样式定义
		        styles: {
		            'style_blue': new TMap.PolylineStyle({
		                'color': '#3777FF', //线填充色
		                'width': 6, //折线宽度
		                'borderWidth': 5, //边线宽度
		                'borderColor': '#FFF', //边线颜色
		                'lineCap': 'round' //线端头方式
		            }),
		        },
		        //折线数据定义
		        geometries: [
		            {
		                'id': 'pl_1',//折线唯一标识，删除时使用
		                'styleId': 'style_blue',//绑定样式名
		                'paths': pl
		            }
		        ]
		    });
		},
	// 设置自适应显示marker
	    selfAdaptionMarker(markersArr) {
	      let bounds = new TMap.LatLngBounds();
	      markersArr.forEach(item => {
	        if (bounds.isEmpty() || !bounds.contains(item.position)) {
	          bounds.extend(item.position);
	        }
	      });
	      //   设置地图可是范围
	      this.map.fitBounds(bounds, {
	        padding: 100 //自适应边距
	      });
	    }  
    }
}
</script>

<style scoped>
    #Home {
    }

    #atlas {
		width: 100%;
		height: 93%;
		position: absolute;
		margin-top: 46px;
    }
</style>
